package cn.ldw.test;

public class HeadSort2 {
    public static void main(String[] args) {
        int[] nums = {3, 0, -1, 3, 7, 5};
        sort(nums);
        for (int num : nums) {
            System.out.println(num);
        }
    }
    //构建堆
    public static void sort(int[] nums) {
        int len = nums.length;
        for(int i = len / 2 - 1; i >= 0; i--) {
            adjust(nums, i, len);
        }
        for(int i = len - 1; i > 0; i--) {
            swap(nums, i, 0);
            adjust(nums, 0, i);
        }
    }

    //调整堆
    public static void adjust(int[] nums, int i, int len) {
        int temp = nums[i];
        for(int j = i * 2 + 1; j < len; j = j * 2 + 1) {
            if(j + 1< len && nums[j + 1] > nums[j]) {
                j++;
            }
            if(nums[j] > nums[i]) {
                nums[i] = nums[j];
                i = j;
            }
        }
        nums[i] = temp;
    }
    //交换
    public static void swap(int[] nums, int i, int j) {
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }

}
